# -*- coding: utf-8 -*-
# @Time    : 2022/7/20 10:24
# @Author  : Yanfeng
# @Email   : sxyanfeng2014@163.com
# @File    : __init__.py.py
# @Software: PyCharm

import base64
import hashlib
import hmac
import time
import urllib.parse
from typing import Any
from dingtalkchatbot.chatbot import DingtalkChatbot, FeedLink
from util.otherutils.get_conf_data import project_name, tester_name
from common.dir_config import ConfigHandler
from util.otherutils.allureDate.allure_report_data import CaseCount
from util.otherutils.localIpControl import get_host_ip
from util.readFileUtils.yamlControl import GetYamlData
from util.times_tool.time_control import now_time, now_time_day


class DingTalkSendMsg(object):

    def __init__(self, DingTalk="DingTalk"):
        self.DingTalk = DingTalk
        self.timeStamp = str(round(time.time() * 1000))
        self.sign = self.get_sign()
        self.devConfig = ConfigHandler()
        # 从yaml文件中获取钉钉配置信息
        self.getDingTalk = GetYamlData(self.devConfig.yaml_dir).get_yaml_data()[self.DingTalk]

        # 获取 webhook地址
        self.webhook = self.getDingTalk["webhook"] + "&timestamp=" + self.timeStamp + "&sign=" + self.sign
        self.xiaoDing = DingtalkChatbot(self.webhook)
        self.Process = CaseCount()

    def get_sign(self) -> str:
        """
        根据时间戳 + "sign" 生成密钥
        :return:
        """
        secret = GetYamlData(ConfigHandler().yaml_dir).get_yaml_data()[self.DingTalk]['secret']
        string_to_sign = '{}\n{}'.format(self.timeStamp, secret).encode('utf-8')
        hmac_code = hmac.new(secret.encode('utf-8'), string_to_sign, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        return sign

    def send_text(self, msg: str, mobiles=None) -> None:
        """
        发送文本信息
        :param msg: 文本内容
        :param mobiles: 艾特用户电话
        :return:
        """
        if not mobiles:
            self.xiaoDing.send_text(msg=msg, is_at_all=True)
        else:
            if isinstance(mobiles, list):
                self.xiaoDing.send_text(msg=msg, at_mobiles=mobiles)
            else:
                raise TypeError("mobiles类型错误 不是list类型.")

    def send_link(self, title: str, text: str, message_url: str, pic_url: str) -> None:
        """
        发送link通知
        :return:
        """
        try:
            self.xiaoDing.send_link(title=title, text=text, message_url=message_url, pic_url=pic_url)
        except Exception:
            raise

    def send_markdown(self, title: str, msg: str, mobiles=None, is_at_all=False) -> None:
        """

        :param is_at_all:
        :param mobiles:
        :param title:
        :param msg:
        markdown 格式
        """

        if mobiles is None:
            self.xiaoDing.send_markdown(title=title, text=msg, is_at_all=is_at_all)
        else:
            if isinstance(mobiles, list):
                self.xiaoDing.send_markdown(title=title, text=msg, at_mobiles=mobiles)
            else:
                raise TypeError("mobiles类型错误 不是list类型.")

    @staticmethod
    def feed_link(title: str, message_url: str, pic_url: str) -> Any:

        return FeedLink(title=title, message_url=message_url, pic_url=pic_url)

    def send_feed_link(self, *arg) -> None:
        try:
            self.xiaoDing.send_feed_card(list(arg))
        except Exception:
            raise

    def send_ding_notification(self):
        # 发送钉钉通知
        text = f"#### {project_name}自动化通知  \n\n>Python脚本任务: {project_name}\n\n>环境: TEST\n\n>" \
               f"执行人: {tester_name}\n\n>执行结果: {self.Process.pass_rate()}% \n\n>总用例数: {self.Process.total_count()} " \
               f"\n\n>成功用例数: {self.Process.pass_count()}" \
               f" \n\n>失败用例数: {self.Process.failed_count()} \n\n>跳过用例数: {self.Process.skipped_count()}" \
               f" ![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png)\n" \
            # f" > ###### 测试报告 [详情](http://{get_host_ip()}:9999/index.html) \n"
        DingTalkSendMsg(self.DingTalk).send_markdown(
            title="【接口自动化通知】",
            msg=text
        )

    def send_success(self, text, title, phone_list):
        time = now_time()
        text1 = f" {title}  \n" \
                f" 执行时间:  <font color='red' size='5'>{time}  </font>     \n" \
                f"{text} \n"
                # f"![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png)   \n"
        DingTalkSendMsg(self.DingTalk).send_markdown(
            title=title,
            msg=text1,
            mobiles=phone_list
        )

    def send_error(self, text, title, phone_list):
        time = now_time()
        text1 = f"{title}  \n" \
                f"执行时间:  {time}       \n" \
                f"{text} \n" \
                f"![screenshot](https://img95.699pic.com/xsj/07/1s/fh.jpg%21/fh/300)   \n"
        DingTalkSendMsg(self.DingTalk).send_markdown(
            title=title,
            msg=text1,
            mobiles=phone_list
        )

    def send_category_monitoring(self, text):

        time = now_time()
        text_report = f"本周类目采集数据同步服务监控\n" \
                      f"执行时间:  {time}       \n" \
                      f"{text}                 \n" \
                      f"![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png)"
        DingTalkSendMsg().send_markdown(
            title="类目服务监控",
            msg=text_report,
            mobiles=[13824861341]
        )

    def send_migration_report(self, text, images):

        time = now_time_day()
        webhook = 'https://oapi.dingtalk.com/robot/send?access_token=b33f9811fddbca0ac1a9224f31198025273d25d9b1efdab38364dcb7b6b45b3c'
        secret = 'SEC5f323286971857a1a70f9d26be737c3948390d9f8aad9503630a749a344f4ea0'
        text_report = f"Listing迁移服务监控   \n" \
                      f"{time}       \n" \
                      f"       \n" \
                      f"{text}                 \n" \
                      f"{images}"

        DingtalkChatbot(webhook, secret).send_markdown(
            title='Listing迁移服务监控',
            text=text_report,
            at_mobiles=[13824861341, 15323860746, 17820398321, 13670292647]
        )


if __name__ == '__main__':
    text = '迁移测试'
    DingTalkSendMsg().send_migration_report(text)
